package org.example.votingsystem.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.votingsystem.account.Account;
import org.example.votingsystem.account.Result;
import org.example.votingsystem.dao.AccountDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;


@WebServlet("/sign")
public class Sign extends HttpServlet {
    private AccountDao accountDao = new AccountDao();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String mark = req.getParameter("mark");

//        check if the user is logged in
        if("check".equals(mark)) {
            // check if the user has voted for the candidate
            // if yes, return true
            String id = req.getParameter("id");
            try {
                System.out.println("开始验证");
                if(accountDao.isIdExist(id)){
                    Result result = new Result(200,"存在",null);
                    resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
                }else{
                    Result result = new Result(201,"不存在",null);
                    resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
                }
            } catch (SQLException e) {
                    Result result = new Result(500,"服务器内部错误",null);
                    resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
            }
        }else if("register".equals(mark)){
            // register the user
            String name = req.getParameter("name");
            String password = req.getParameter("pass");
            String id = req.getParameter("id");
            Account account = new Account();
            account.setName(name);
            account.setPassword(password);
            account.setId(id);
            try {
                accountDao.registerAccount(account);
                Result result = new Result(200,"注册成功",null);
                resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
            }catch (Exception e){
                Result result = new Result(500,"系统错误",null);
                resp.getWriter().print(new ObjectMapper().writeValueAsString(result));
            }
        }
    }
}
